#include "netlib/net/event/channel.h"

#include <sys/poll.h>

#include "netlib/net/event/event_loop.h"

const int netlib::net::Channel::kNoneEvent = 0;
const int netlib::net::Channel::kReadEvent = POLLIN | POLLPRI;
const int netlib::net::Channel::kWriteEvent = POLLOUT;

void netlib::net::Channel::HandleEvent(Timestamp time) {
	is_handling_ = true;
	if (revents_ & POLLNVAL) {
		return;
	}

	// if ((revents_ & POLLHUP) && !(revents_ & POLLIN)) {
	// 	LOG_WARN << "Channel::handleEvent() POLLHUB";
	// 	if (close_callback_) close_callback_();
	// }
	if (revents_ & (POLLERR | POLLNVAL)) {
		if (error_callback_) {
			error_callback_();
		}
	}
	if (events_ & revents_ & (kReadEvent | POLLRDHUP)) {
		if (read_callback_) {
			read_callback_(time);
		}
	}
	if (events_ & revents_ & POLLOUT) {
		if (write_callback_) {
			write_callback_();
		}
	}
	is_handling_ = false;
}

void netlib::net::Channel::Remove() {
	assert(IsNoneEvent());
	// is_added_to_loop_ = false;
	loop_->RemoveChannel(this);
}

void netlib::net::Channel::Update() { loop_->UpdateChannel(this); }
